<template>
  <div class="traffic-monitor" :class="{ 'mobile-layout': isMobileDevice }">
    <el-container>
      <!-- 移动端顶部导航栏 -->
      <el-header class="mobile-header" v-if="isMobileDevice">
        <div class="mobile-header-content">
          <h1>流量监控</h1>
          <div class="mobile-user-actions">
            <el-dropdown trigger="click">
              <el-button type="text" class="mobile-user-btn">
                <el-icon><User /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item disabled>{{ userStore.user?.username }}</el-dropdown-item>
                  <el-dropdown-item 
                    v-if="userStore.user?.isAdmin" 
                    @click="$router.push('/admin')"
                  >
                    <el-icon><Setting /></el-icon> 管理面板
                  </el-dropdown-item>
                  <el-dropdown-item 
                    v-if="canUserInvite" 
                    @click="showInviteDialog = true"
                  >
                    <el-icon><UserFilled /></el-icon> 生成邀请码
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon><SwitchButton /></el-icon> 退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <!-- 桌面端头部 -->
      <el-header v-else class="desktop-header">
        <div class="header-content">
          <h1>流量监控系统</h1>
          <div class="user-actions">
            <div class="user-info">
              <span>欢迎，{{ userStore.user?.username }}</span>
            </div>
            <el-button 
              v-if="userStore.user?.isAdmin" 
              type="text" 
              @click="$router.push('/admin')"
              class="admin-btn"
            >
              <el-icon><Setting /></el-icon>
              管理面板
            </el-button>
            <el-button 
              v-if="canUserInvite" 
              type="text" 
              @click="showInviteDialog = true"
              class="invite-btn"
            >
              <el-icon><UserFilled /></el-icon>
              生成邀请码
            </el-button>
            <el-button type="text" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-button>
          </div>
        </div>
      </el-header>

      <el-main class="main-content" :class="{ 'desktop-main': !isMobileDevice }">
        <!-- 移动端标签导航 -->
        <div v-if="isMobileDevice" class="mobile-tabs">
          <div class="mobile-tab-nav">
            <div 
              v-for="tab in tabs" 
              :key="tab.name"
              :class="['mobile-tab-item', { active: activeTab === tab.name }]"
              @click="activeTab = tab.name"
            >
              <el-icon>
                <component :is="tab.icon" />
              </el-icon>
              <span>{{ tab.label }}</span>
            </div>
          </div>
        </div>

        <!-- 移动端内容区域 -->
        <div v-if="isMobileDevice" class="mobile-content">
          <!-- 配置Tab内容 -->
          <div v-show="activeTab === 'config'" class="mobile-tab-content">
            <!-- 移动端提示信息区域 -->
            <NotificationBanner />
            
            <div class="mobile-form">
              <div class="mobile-form-header">
                <h3>流量监控配置</h3>
              </div>
              <el-form
                ref="configFormRef"
                :model="configForm"
                :rules="configRules"
                label-position="top"
                class="mobile-config-form"
              >
                <FormField
                  type="input"
                  label="Token"
                  prop="token"
                  v-model="configForm.token"
                  placeholder="请输入Token"
                  :rules="configRules.token"
                />
                
                <FormField
                  type="input"
                  label="手机号"
                  prop="phone"
                  v-model="configForm.phone"
                  placeholder="请输入手机号"
                  :rules="configRules.phone"
                />
                
                <FormField
                  type="select"
                  label="运营商"
                  prop="operator"
                  v-model="configForm.operator"
                  placeholder="请选择运营商"
                  :options="operatorOptions"
                  :rules="configRules.operator"
                />
                
                <FormField
                  type="input"
                  label="App ID"
                  prop="appId"
                  v-model="configForm.appId"
                  placeholder="请输入App ID（可选）"
                />

                <div class="mobile-form-actions">
                  <el-button
                    type="primary"
                    size="large"
                    :loading="submitLoading"
                    @click="handleSubmitConfig"
                    class="mobile-submit-btn"
                  >
                    保存配置
                  </el-button>
                </div>
              </el-form>
            </div>
          </div>

          <!-- 删除记录Tab内容 -->
          <div v-show="activeTab === 'delete'" class="mobile-tab-content">
            <div class="mobile-form">
              <div class="mobile-form-header">
                <h3>配置记录管理</h3>
                <div class="mobile-actions">
                  <el-button type="warning" size="small" @click="handleCleanupHistory" :loading="cleanupLoading">
                    清理历史
                  </el-button>
                  <el-button type="primary" size="small" @click="loadConfigs">
                    刷新
                  </el-button>
                </div>
              </div>

              <div class="mobile-table-container">
                <div v-if="configs.length > 0" class="config-list">
                  <div 
                    v-for="config in configs" 
                    :key="config.id" 
                    class="config-item"
                  >
                    <div class="config-info">
                      <div class="config-phone">{{ maskPhoneNumber(config.phone) }}</div>
                      <div class="config-meta">
                        <span class="config-operator">{{ config.operator }}</span>
                        <span class="config-time">{{ config.created_at }}</span>
                      </div>
                    </div>
                    <div class="config-actions">
                      <el-button
                        type="primary"
                        size="small"
                        @click="viewTrafficDetail(config.id)"
                      >
                        详情
                      </el-button>
                      <el-button
                        type="danger"
                        size="small"
                        :loading="deleteLoading"
                        @click="handleDeleteConfig(config.id)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                </div>
                <div v-else class="mobile-empty">
                  暂无配置记录
                </div>
              </div>
            </div>
          </div>

          <!-- 后台管理Tab内容 -->
          <div v-show="activeTab === 'manage'" class="mobile-tab-content">
            <div class="mobile-form">
              <div class="mobile-form-header">
                <h3>监控链接生成</h3>
              </div>

              <el-form label-position="top">
                <el-form-item label="选择配置">
                  <el-select 
                    v-model="selectedConfigId" 
                    placeholder="请选择配置" 
                    style="width: 100%"
                    @change="handleConfigChange"
                  >
                    <el-option
                      v-for="config in configs"
                      :key="config.id"
                      :label="`${maskPhoneNumber(config.phone)} (${config.operator})`"
                      :value="config.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    size="large"
                    :disabled="!selectedConfigId"
                    :loading="generateLoading"
                    @click="handleGenerateUrl"
                    class="mobile-submit-btn"
                  >
                    生成监控链接
                  </el-button>
                </el-form-item>

                <!-- 新生成链接 -->
                <div v-if="monitorUrl" class="mobile-link-section">
                  <h4>新生成链接</h4>
                  <div class="mobile-link-item">
                    <el-input
                      v-model="monitorUrl"
                      readonly
                      type="textarea"
                      :rows="3"
                      class="mobile-link-input"
                    />
                    <div class="mobile-link-actions">
                      <el-button @click="copyUrl" size="small">复制</el-button>
                      <el-button type="primary" @click="viewTrafficDetail(selectedConfigId)" size="small">查看详情</el-button>
                      <el-button type="success" @click="openUrl" size="small">访问链接</el-button>
                    </div>
                  </div>
                </div>

                <!-- 历史链接 -->
                <div v-if="selectedConfigId" class="mobile-link-section">
                  <h4>历史链接</h4>
                  <div v-if="monitorLinks.length > 0" class="history-links">
                    <div 
                      v-for="link in monitorLinks" 
                      :key="link.id"
                      class="mobile-link-item"
                    >
                      <div class="link-time">{{ formatTime(link.created_at) }}</div>
                      <el-input
                        :value="link.monitor_url"
                        readonly
                        type="textarea"
                        :rows="2"
                        class="mobile-link-input"
                      />
                      <div class="mobile-link-actions">
                        <el-button size="small" @click="copySpecificUrl(link.monitor_url)">复制</el-button>
                        <el-button type="success" size="small" @click="openSpecificUrl(link.monitor_url)">访问</el-button>
                      </div>
                    </div>
                  </div>
                  <div v-else class="mobile-empty">
                    该配置暂无历史监控链接
                  </div>
                </div>
              </el-form>
            </div>
          </div>
        </div>

        <!-- 桌面端内容区域 -->
        <div v-else class="desktop-content">
          <el-tabs v-model="activeTab" class="desktop-tabs">
            <!-- 登录配置标签 -->
            <el-tab-pane label="登录配置" name="config">
              <!-- 提示信息区域 -->
              <NotificationBanner />
              
              <div class="desktop-card">
                <div class="desktop-card-header">
                  流量监控配置
                </div>
                <div class="desktop-card-body">

                  <el-form
                    ref="configFormRef"
                    :model="configForm"
                    :rules="configRules"
                    label-width="100px"
                    class="desktop-form"
                  >
                <FormField
                  type="input"
                  label="Token"
                  prop="token"
                  v-model="configForm.token"
                  placeholder="请输入Token"
                  :rules="configRules.token"
                />
                
                <FormField
                  type="input"
                  label="手机号"
                  prop="phone"
                  v-model="configForm.phone"
                  placeholder="请输入手机号"
                  :rules="configRules.phone"
                />
                
                <FormField
                  type="select"
                  label="运营商"
                  prop="operator"
                  v-model="configForm.operator"
                  placeholder="请选择运营商"
                  :options="operatorOptions"
                  :rules="configRules.operator"
                />
                
                <FormField
                  type="input"
                  label="App ID"
                  prop="appId"
                  v-model="configForm.appId"
                  placeholder="请输入App ID（可选）"
                />

                    <el-form-item>
                      <div class="desktop-button-group">
                        <el-button
                          type="primary"
                          :loading="submitLoading"
                          @click="handleSubmitConfig"
                        >
                          保存配置
                        </el-button>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </el-tab-pane>

            <!-- 删除记录标签 -->
            <el-tab-pane label="删除记录" name="delete">
              <div class="desktop-action-bar">
                <h2>配置记录管理</h2>
                <div class="actions">
                  <el-button type="warning" @click="handleCleanupHistory" :loading="cleanupLoading">
                    清理历史记录
                  </el-button>
                  <el-button type="primary" @click="loadConfigs">
                    刷新
                  </el-button>
                </div>
              </div>
              
              <div class="desktop-table">

                <el-table :data="configs" style="width: 100%" size="small" stripe>
                  <el-table-column prop="phone" label="手机号" />
                  <el-table-column prop="operator" label="运营商" />
                  <el-table-column prop="created_at" label="创建时间" />
                  <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                      <div class="desktop-button-group">
                        <el-button
                          type="primary"
                          size="small"
                          @click="viewTrafficDetail(row.id)"
                        >
                          查看详情
                        </el-button>
                        <el-button
                          type="danger"
                          size="small"
                          :loading="deleteLoading"
                          @click="handleDeleteConfig(row.id)"
                        >
                          删除
                        </el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>

            <!-- 后台管理标签 -->
            <el-tab-pane label="后台管理" name="manage">
              <div class="desktop-card">
                <div class="desktop-card-header">
                  监控链接生成
                </div>
                <div class="desktop-card-body">

                  <el-form label-width="100px" class="desktop-form">
                <el-form-item label="选择配置">
                  <el-select 
                    v-model="selectedConfigId" 
                    placeholder="请选择配置" 
                    style="width: 100%"
                    @change="handleConfigChange"
                  >
                    <el-option
                      v-for="config in configs"
                      :key="config.id"
                      :label="`${maskPhoneNumber(config.phone)} (${config.operator})`"
                      :value="config.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    :disabled="!selectedConfigId"
                    :loading="generateLoading"
                    @click="handleGenerateUrl"
                  >
                    生成监控链接
                  </el-button>
                </el-form-item>

                <el-form-item v-if="monitorUrl" label="新生成链接">
                  <el-input
                    v-model="monitorUrl"
                    readonly
                    style="margin-bottom: 10px;"
                  >
                    <template #append>
                      <el-button @click="copyUrl">复制</el-button>
                    </template>
                  </el-input>
                  <el-button type="primary" @click="viewTrafficDetail(selectedConfigId)" style="margin-right: 8px;">查看详情</el-button>
                  <el-button type="success" @click="openUrl">访问链接</el-button>
                </el-form-item>

                <el-form-item v-if="selectedConfigId" label="历史链接">
                  <div v-if="monitorLinks.length > 0">
                    <el-table :data="monitorLinks" style="width: 100%" size="small" stripe height="300">
                      <el-table-column prop="monitor_url" label="监控链接" min-width="350">
                        <template #default="{ row }">
                          <div class="link-container">
                            <el-text class="link-text" truncated>{{ row.monitor_url }}</el-text>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column prop="created_at" label="创建时间" width="130">
                        <template #default="{ row }">
                          <el-text size="small">{{ formatTime(row.created_at) }}</el-text>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="140" fixed="right">
                        <template #default="{ row }">
                          <el-button-group size="small">
                            <el-button
                              size="small"
                              @click="copySpecificUrl(row.monitor_url)"
                            >
                              复制
                            </el-button>
                            <el-button
                              type="success"
                              size="small"
                              @click="openSpecificUrl(row.monitor_url)"
                            >
                              访问
                            </el-button>
                          </el-button-group>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <div v-else class="no-links-tip">
                    <el-text type="info" size="small">该配置暂无历史监控链接</el-text>
                  </div>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </el-container>

        <!-- 邀请码管理对话框 -->
    <el-dialog 
      v-model="showInviteDialog" 
      :title="isMobileDevice ? '邀请码' : '邀请码管理'" 
      :width="isMobileDevice ? '95%' : '800px'"
      :close-on-click-modal="false"
      @close="handleInviteDialogClose"
      @open="handleInviteDialogOpen"
      class="invite-dialog"
    >
      <div class="invite-container" :class="{ 'mobile-invite': isMobileDevice }">
        <!-- 生成邀请码区域 -->
        <div class="invite-generate-section">
          <div class="section-header">
            <h3>
              <el-icon><UserFilled /></el-icon>
              生成邀请码
            </h3>
            <p>快速生成新的邀请码，用于邀请新用户注册</p>
          </div>
          
          <div class="generate-actions">
            <el-button 
              type="primary" 
              @click="handleQuickGenerate('normal')"
              :loading="generatingInvite"
              :size="isMobileDevice ? 'default' : 'large'"
              class="generate-btn"
            >
              <el-icon><Plus /></el-icon>
              {{ generatingInvite ? '生成中...' : '生成邀请码' }}
            </el-button>
          </div>

          <!-- 生成结果 -->
          <div v-if="generatedInviteCodes.length > 0" class="invite-result">
            <el-alert
              title="邀请码生成成功"
              type="success"
              :closable="false"
              show-icon
              class="success-alert"
            >
              <template #default>
                <div class="alert-content">
                  <p>邀请码已生成，您可以复制分享给朋友使用</p>
                  <div class="alert-actions">
                    <el-button 
                      size="small" 
                      type="success" 
                      @click="copyAllGeneratedCodes"
                      :icon="DocumentCopy"
                    >
                      复制所有
                    </el-button>
                  </div>
                </div>
              </template>
            </el-alert>
            <div class="result-cards">
              <div 
                v-for="(code, index) in generatedInviteCodes" 
                :key="index"
                class="result-card"
                :style="{ animationDelay: `${index * 0.1}s` }"
              >
                <div class="code-display">
                  <div class="code-info">
                    <span class="code-label">邀请码</span>
                    <span class="code-text">{{ code }}</span>
                  </div>
                  <el-button 
                    @click="copyInviteCode(code)" 
                    :size="isMobileDevice ? 'small' : 'default'"
                    type="primary"
                    :icon="DocumentCopy"
                    class="copy-btn"
                  >
                    复制
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分隔线 -->
        <el-divider>
          <el-icon><List /></el-icon>
          我的邀请码
        </el-divider>

        <!-- 我的邀请码列表 -->
        <div class="invite-list-section">
          <div class="list-header">
            <div class="list-info">
              <h3>
                <el-icon><List /></el-icon>
                我的邀请码
              </h3>
              <p>查看和管理您创建的所有邀请码</p>
            </div>
            <el-button 
              @click="loadMyInviteCodes" 
              :loading="loadingMyInviteCodes" 
              :size="isMobileDevice ? 'small' : 'default'"
              type="text"
              class="refresh-btn"
            >
              <el-icon><Refresh /></el-icon>
              {{ isMobileDevice ? '' : '刷新' }}
            </el-button>
          </div>
          
          <!-- 邀请码统计 -->
          <div v-if="myInviteCodes.length > 0" class="invite-stats">
            <div class="stat-item">
              <span class="stat-number">{{ myInviteCodes.length }}</span>
              <span class="stat-label">总数</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ myInviteCodes.filter(code => !code.is_used).length }}</span>
              <span class="stat-label">可用</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ myInviteCodes.filter(code => code.is_used).length }}</span>
              <span class="stat-label">已使用</span>
            </div>
          </div>
          
          <!-- 邀请码列表 -->
          <div class="invite-codes-list">
            <div v-if="loadingMyInviteCodes" class="loading-container">
              <el-skeleton :rows="3" animated />
            </div>
            
            <div v-else-if="myInviteCodes.length === 0" class="no-invite-codes">
              <el-empty description="暂无邀请码">
                <template #image>
                  <el-icon size="60" color="#c0c4cc"><UserFilled /></el-icon>
                </template>
                <el-button type="primary" @click="handleQuickGenerate('normal')" :loading="generatingInvite">
                  生成第一个邀请码
                </el-button>
              </el-empty>
            </div>
            
            <div v-else class="codes-grid">
              <div 
                v-for="code in myInviteCodes" 
                :key="code.id"
                class="code-card"
                :class="{ 'used': code.is_used }"
              >
                <div class="code-header">
                  <div class="code-status">
                    <el-tag 
                      :type="code.is_used ? 'success' : 'warning'" 
                      :size="isMobileDevice ? 'small' : 'default'"
                    >
                      {{ code.is_used ? '已使用' : '可用' }}
                    </el-tag>
                  </div>
                  <div class="code-actions">
                    <el-button 
                      @click="copyInviteCode(code.code)"
                      :size="isMobileDevice ? 'small' : 'default'"
                      type="text"
                      :icon="DocumentCopy"
                      class="action-btn"
                      :disabled="code.is_used"
                      title="复制邀请码"
                    />
                    <el-button 
                      @click="shareInviteCode(code.code)"
                      :size="isMobileDevice ? 'small' : 'default'"
                      type="text"
                      :icon="Share"
                      class="action-btn"
                      :disabled="code.is_used"
                      title="分享邀请码"
                    />
                  </div>
                </div>
                
                <div class="code-content">
                  <div class="code-value">{{ code.code }}</div>
                  <div class="code-meta">
                    <div class="meta-item">
                      <el-icon><Calendar /></el-icon>
                      <span>{{ formatTime(code.created_at) }}</span>
                    </div>
                    <div v-if="code.is_used" class="meta-item">
                      <el-icon><Check /></el-icon>
                      <span>使用于 {{ formatTime(code.used_at) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showInviteDialog = false" :size="isMobileDevice ? 'default' : 'large'">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  SwitchButton, 
  Setting, 
  Delete, 
  Monitor,
  Document,
  UserFilled,
  Plus,
  DocumentCopy,
  Refresh,
  List,
  Calendar,
  Check,
  Share
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  submitTrafficConfig,
  deleteTrafficConfig,
  generateMonitorUrl,
  getTrafficConfigs,
  cleanupHistory,
  getMonitorLinks,
  deleteMonitorLink
} from '@/api/traffic'
import { generateInviteCode, getSystemConfig, getMyInviteCodes } from '@/api/auth'
import { usePhoneMask } from '@/utils/phoneUtils'
import FormField from '@/components/FormField.vue'
import NotificationBanner from '@/components/NotificationBanner.vue'

const router = useRouter()
const userStore = useUserStore()

// 手机号码脱敏工具
const { maskPhoneNumber } = usePhoneMask()

const activeTab = ref('config')
const configFormRef = ref()
const submitLoading = ref(false)
const deleteLoading = ref(false)
const generateLoading = ref(false)
const cleanupLoading = ref(false)
const configs = ref([])
const selectedConfigId = ref('')
const monitorUrl = ref('')
const monitorLinks = ref([])

// 邀请码相关状态
const showInviteDialog = ref(false)
const generatingInvite = ref(false)
const generatedInviteCodes = ref([])
const myInviteCodes = ref([])
const loadingMyInviteCodes = ref(false)
const systemConfig = ref({
  allowAllInvite: false
})



// 设备类型检测
const isMobileDevice = computed(() => {
  return window.innerWidth <= 768 || document.body.classList.contains('mobile-device')
})

const isTabletDevice = computed(() => {
  return window.innerWidth > 768 && window.innerWidth <= 1024 || document.body.classList.contains('tablet-device')
})

const isDesktopDevice = computed(() => {
  return window.innerWidth > 1024 || document.body.classList.contains('desktop-device')
})

// 检查用户是否可以邀请
const canUserInvite = computed(() => {
  const user = userStore.user
  if (!user) return false
  
  // 管理员总是可以邀请
  if (user.isAdmin) return true
  
  // 如果开启了全局邀请权限，所有用户都可以邀请
  if (systemConfig.value.allowAllInvite) return true
  
  // 否则只有被单独授权的用户可以邀请
  return user.canInvite
})

// 标签配置
const tabs = ref([
  { name: 'config', label: '配置', icon: Setting },
  { name: 'delete', label: '记录', icon: Document },
  { name: 'manage', label: '链接', icon: Monitor }
])

const configForm = reactive({
  token: '',
  phone: '',
  operator: '联通',
  appId: ''
})

const operatorOptions = [
  { label: '联通', value: '联通' },
  { label: '移动', value: '移动' },
  { label: '电信', value: '电信' }
]

const configRules = {
  token: [
    { required: true, message: '请输入Token', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  operator: [
    { required: true, message: '请选择运营商', trigger: 'change' }
  ]
}

const handleSubmitConfig = async () => {
  if (!configFormRef.value) return
  
  try {
    await configFormRef.value.validate()
    submitLoading.value = true
    
    await submitTrafficConfig(configForm)
    
    ElMessage.success('配置保存成功')
    
    // 重置表单
    configFormRef.value.resetFields()
    
    // 刷新配置列表
    await loadConfigs()
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error(error.message || '保存配置失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDeleteConfig = async (configId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个配置吗？', '确认删除', {
      type: 'warning'
    })
    
    deleteLoading.value = true
    await deleteTrafficConfig(configId)
    
    ElMessage.success('配置删除成功')
    await loadConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除配置失败:', error)
      ElMessage.error(error.message || '删除配置失败')
    }
  } finally {
    deleteLoading.value = false
  }
}

const handleGenerateUrl = async () => {
  try {
    generateLoading.value = true
    const response = await generateMonitorUrl(selectedConfigId.value)
    
    monitorUrl.value = response.monitorUrl
    ElMessage.success('监控链接生成成功')
    
    // 自动刷新历史链接列表
    await loadMonitorLinks(selectedConfigId.value)
  } catch (error) {
    console.error('生成链接失败:', error)
    ElMessage.error(error.message || '生成链接失败')
  } finally {
    generateLoading.value = false
  }
}

const copyUrl = async () => {
  try {
    await navigator.clipboard.writeText(monitorUrl.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const openUrl = () => {
  window.open(monitorUrl.value, '_blank')
}

const openSpecificUrl = (url) => {
  window.open(url, '_blank')
}

const copySpecificUrl = async (url) => {
  try {
    await navigator.clipboard.writeText(url)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const viewTrafficDetail = (configId) => {
  router.push(`/traffic-detail/${configId}`)
}

const handleConfigChange = (configId) => {
  // 清空之前的数据
  monitorUrl.value = ''
  monitorLinks.value = []
  
  // 自动加载历史链接
  if (configId) {
    loadMonitorLinks(configId)
  }
}

const loadMonitorLinks = async (configId = selectedConfigId.value) => {
  if (!configId) {
    return
  }
  
  try {
    const response = await getMonitorLinks(configId)
    // console.log(response)
    monitorLinks.value = response.data
    if (response.length > 0) {
      // console.log(`自动加载了 ${response.length} 条历史链接`)
    }
  } catch (error) {
    console.error('加载监控链接失败:', error)
    // 不显示错误提示，避免干扰用户体验
  }
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN', {
    timeZone: 'Asia/Shanghai'
  })
}

const loadConfigs = async () => {
  try {
    const response = await getTrafficConfigs()
    configs.value = response.data
  } catch (error) {
    console.error('加载配置失败:', error)
  }
}

const handleCleanupHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清理所有配置的历史记录吗？每个配置将只保留最新的10条记录。',
      '确认清理',
      {
        type: 'warning',
        confirmButtonText: '确认清理',
        cancelButtonText: '取消'
      }
    )
    
    cleanupLoading.value = true
    const response = await cleanupHistory()
    
    ElMessage.success(`清理完成！处理了 ${response.cleanedConfigs} 个配置`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理历史记录失败:', error)
      ElMessage.error(error.message || '清理历史记录失败')
    }
  } finally {
    cleanupLoading.value = false
  }
}

// 快速生成邀请码
const handleQuickGenerate = async (type) => {
  try {
    generatingInvite.value = true
    
    const options = {
      count: 1,
      inviteType: 'INVITE',
      description: '普通用户邀请码'
    }
    
    const response = await generateInviteCode(options)
    
    generatedInviteCodes.value = response.inviteCodes
    ElMessage.success(`成功生成${response.count}个邀请码`)
    
    // 刷新邀请码列表
    await loadMyInviteCodes()
  } catch (error) {
    console.error('生成邀请码失败:', error)
    ElMessage.error(error.response?.data?.message || '生成邀请码失败')
  } finally {
    generatingInvite.value = false
  }
}

// 复制邀请码
const copyInviteCode = async (code) => {
  const textToCopy = code || generatedInviteCode.value
  if (!textToCopy) {
    ElMessage.error('没有可复制的邀请码')
    return
  }
  
  try {
    // 优先使用现代 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(textToCopy)
      ElMessage.success('邀请码已复制到剪贴板')
    } else {
      // 降级方案：使用传统的 document.execCommand
      const textArea = document.createElement('textarea')
      textArea.value = textToCopy
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      const successful = document.execCommand('copy')
      document.body.removeChild(textArea)
      
      if (successful) {
        ElMessage.success('邀请码已复制到剪贴板')
      } else {
        throw new Error('execCommand failed')
      }
    }
  } catch (error) {
    console.error('复制失败:', error)
    // 最后的降级方案：显示邀请码让用户手动复制
    ElMessageBox.alert(
      `邀请码：${textToCopy}`,
      '复制失败，请手动复制',
      {
        confirmButtonText: '确定',
        type: 'warning'
      }
    )
  }
}

// 复制所有生成的邀请码
const copyAllGeneratedCodes = async () => {
  if (generatedInviteCodes.value.length === 0) {
    ElMessage.error('没有可复制的邀请码')
    return
  }
  
  const allCodes = generatedInviteCodes.value.join('\n')
  await copyInviteCode(allCodes)
}

// 分享邀请码
const shareInviteCode = async (code) => {
  const shareText = `邀请您加入流量监控系统！\n邀请码：${code}\n\n请使用此邀请码注册账号，享受流量监控服务。`
  
  try {
    // 检查是否支持 Web Share API
    if (navigator.share && navigator.canShare && navigator.canShare({ text: shareText })) {
      await navigator.share({
        title: '流量监控系统邀请',
        text: shareText
      })
      ElMessage.success('分享成功')
    } else {
      // 降级到复制到剪贴板
      await copyInviteCode(shareText)
      ElMessage.success('邀请信息已复制到剪贴板，您可以粘贴分享')
    }
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('分享失败:', error)
      // 最后的降级方案：复制到剪贴板
      await copyInviteCode(shareText)
      ElMessage.success('邀请信息已复制到剪贴板，您可以粘贴分享')
    }
  }
}

// 加载用户自己的邀请码列表
const loadMyInviteCodes = async () => {
  try {
    loadingMyInviteCodes.value = true
    const response = await getMyInviteCodes()
    myInviteCodes.value = response.inviteCodes
  } catch (error) {
    console.error('加载邀请码列表失败:', error)
    ElMessage.error('加载邀请码列表失败')
  } finally {
    loadingMyInviteCodes.value = false
  }
}



// 邀请码对话框打开处理
const handleInviteDialogOpen = async () => {
  // 自动加载邀请码列表
  await loadMyInviteCodes()
}

// 邀请码对话框关闭处理
const handleInviteDialogClose = () => {
  generatedInviteCodes.value = []
  generatingInvite.value = false
}

// 加载系统配置
const loadSystemConfig = async () => {
  try {
    const response = await getSystemConfig()
    systemConfig.value = response.config
  } catch (error) {
    // 如果获取失败（可能是权限问题），保持默认值
    console.log('获取系统配置失败，可能没有权限')
  }
}

const handleLogout = async () => {
  try {
    await userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
  }
}

onMounted(async () => {
  await loadConfigs()
  // 加载系统配置
  await loadSystemConfig()
  // 如果有预选的配置，自动加载历史链接
  if (selectedConfigId.value) {
    loadMonitorLinks(selectedConfigId.value)
  }
})
</script>

<style scoped>
.traffic-monitor {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.traffic-monitor.mobile-layout {
  background: #f8f9fa;
}

/* 桌面端样式 */
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  color: white;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0 20px;
}

.header-content h1 {
  margin: 0;
  font-size: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.el-main {
  padding: 20px;
}

.el-card {
  margin-bottom: 20px;
}

.no-links-tip {
  padding: 20px;
  text-align: center;
  color: #909399;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
}

/* 移动端样式 */
.mobile-header {
  height: 60px !important;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
  position: sticky;
  top: 20px;
  z-index: 1000;
}

.mobile-header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  color: white;
  padding: 0 16px;
}

.mobile-header-content h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.mobile-user-btn {
  color: white !important;
  font-size: 20px;
}

.main-content {
  flex: 1;
  padding: 0 !important;
  overflow: hidden;
}

.mobile-tabs {
  background: white;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 20px;
  z-index: 999;
}

.mobile-tab-nav {
  display: flex;
  justify-content: space-around;
  padding: 8px 0;
}

.mobile-tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8px 12px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 6px;
  min-width: 60px;
}

.mobile-tab-item.active {
  color: #667eea;
  background-color: #f0f4ff;
}

.mobile-tab-item .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.mobile-tab-item span {
  font-size: 12px;
  font-weight: 500;
}

.mobile-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: 12px;
}

.mobile-tab-content {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.mobile-form {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

.mobile-form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.mobile-form-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.mobile-actions {
  display: flex;
  gap: 8px;
}

.mobile-config-form {
  margin-top: 8px;
}

.mobile-form-actions {
  margin-top: 20px;
}

.mobile-submit-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
}

.mobile-table-container {
  margin-top: 16px;
}

.config-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.config-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #eee;
}

.config-info {
  flex: 1;
}

.config-phone {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.config-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #666;
}

.config-operator {
  background: #e6f4ff;
  color: #1890ff;
  padding: 2px 6px;
  border-radius: 4px;
}

.config-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.mobile-link-section {
  margin-top: 24px;
}

.mobile-link-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.mobile-link-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  border: 1px solid #eee;
}

.link-time {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.mobile-link-input {
  margin-bottom: 12px;
}

.mobile-link-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.history-links {
  max-height: 300px;
  overflow-y: auto;
}

.mobile-empty {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

/* 响应式优化 */
@media (max-width: 480px) {
  .mobile-content {
    padding: 8px;
  }
  
  .mobile-form {
    padding: 16px;
  }
  
  .config-item {
    padding: 12px;
  }
  
  .config-phone {
    font-size: 14px;
  }
  
  .mobile-link-actions {
    justify-content: center;
  }
  
  .mobile-link-actions .el-button {
    flex: 1;
    min-width: 0;
  }
}

/* 桌面端样式保护 */
@media (min-width: 769px) {
  .traffic-monitor:not(.mobile-layout) .el-header {
    height: 60px !important;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    color: white !important;
  }
  
  .traffic-monitor:not(.mobile-layout) .header-content {
    height: 100%;
    color: white;
    padding: 0 20px;
  }
  
  .traffic-monitor:not(.mobile-layout) .header-content h1 {
    color: white;
    font-weight: 600;
  }
  
  .traffic-monitor:not(.mobile-layout) .user-info span {
    color: rgba(255, 255, 255, 0.9);
  }
  
  .traffic-monitor:not(.mobile-layout) .user-info .el-button {
    color: white;
  }
}

/* 桌面端样式 */
.desktop-content {
  padding: 15px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.desktop-card {
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08);
  margin-bottom: 15px;
}

.desktop-card-header {
  padding: 15px 20px 0 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.desktop-card-body {
  padding: 0 20px 15px 20px;
}

.desktop-form {
  max-width: 800px;
}

.desktop-form .el-form-item {
  margin-bottom: 16px;
}

.desktop-form .el-form-item__label {
  font-weight: 500;
  color: #333;
}

.desktop-button-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.desktop-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 15px 20px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08);
}

.desktop-action-bar h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.desktop-action-bar .actions {
  display: flex;
  gap: 12px;
}

.desktop-table {
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08);
  padding: 15px;
}

.desktop-table .el-table {
  border: none;
  background: transparent;
}

.desktop-tabs {
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08);
  padding: 15px;
  min-height: calc(100vh - 100px);
}

.desktop-tabs :deep(.el-tabs__content) {
  height: calc(100% - 45px);
  overflow-y: auto;
  padding-top: 10px;
}

.desktop-tabs :deep(.el-tabs__header) {
  margin: 0 0 10px 0;
}

.desktop-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #e4e7ed;
}

.desktop-tabs :deep(.el-tabs__item) {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  font-weight: 500;
}

.desktop-tabs :deep(.el-tabs__item.is-active) {
  color: #667eea;
}

.desktop-tabs :deep(.el-tabs__active-bar) {
  background-color: #667eea;
}

/* 链接容器样式 */
.link-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.link-text {
  font-size: 12px;
  color: #606266;
  font-family: 'Courier New', monospace;
  line-height: 1.2;
  word-break: break-all;
}

/* 邀请码相关样式 */
.invite-btn {
  color: #67C23A !important;
}

/* 邀请码对话框样式 */
.invite-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.invite-container {
  max-height: 70vh;
  overflow-y: auto;
}

.invite-container.mobile-invite {
  max-height: 80vh;
}

/* 生成邀请码区域 */
.invite-generate-section {
  margin-bottom: 24px;
}

.section-header {
  text-align: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.section-header p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.generate-actions {
  text-align: center;
  margin-bottom: 20px;
}

.generate-btn {
  min-width: 160px;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
}

/* 生成结果样式 */
.invite-result {
  margin-top: 20px;
}

.success-alert {
  margin-bottom: 16px;
}

.alert-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.alert-content p {
  margin: 0;
  flex: 1;
  min-width: 200px;
}

.alert-actions {
  flex-shrink: 0;
}

.result-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 16px;
}

.result-card {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  animation: slideInUp 0.5s ease-out forwards;
  opacity: 0;
  transform: translateY(20px);
}

@keyframes slideInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.code-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.code-info {
  flex: 1;
}

.code-label {
  display: block;
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 4px;
  font-weight: 500;
}

.code-text {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  font-size: 16px;
  color: #67C23A;
  background: #f0f9ff;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #b3d8ff;
  display: inline-block;
}

.copy-btn {
  flex-shrink: 0;
}

/* 分隔线样式 */
.el-divider {
  margin: 24px 0;
}

.el-divider :deep(.el-divider__text) {
  background: #f8f9fa;
  color: #6c757d;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 邀请码列表区域 */
.invite-list-section {
  margin-top: 24px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.list-info h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.list-info p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

.refresh-btn {
  color: #409EFF;
}

/* 邀请码统计 */
.invite-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #6c757d;
  font-weight: 500;
}

/* 邀请码列表 */
.invite-codes-list {
  min-height: 200px;
}

.loading-container {
  padding: 20px;
}

.no-invite-codes {
  text-align: center;
  padding: 40px 20px;
}

.codes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.code-card {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.code-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.code-card.used {
  opacity: 0.7;
  background: #f8f9fa;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.code-status {
  flex: 1;
}

.code-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  color: #409EFF;
  padding: 4px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  color: #337ecc;
  background-color: rgba(64, 158, 255, 0.1);
}

.code-content {
  text-align: center;
}

.code-value {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  font-size: 16px;
  color: #2c3e50;
  background: #f0f9ff;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #b3d8ff;
  margin-bottom: 12px;
  display: inline-block;
  word-break: break-all;
}

.code-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.meta-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 12px;
  color: #6c757d;
}

.meta-item .el-icon {
  font-size: 14px;
}

/* 对话框底部 */
.dialog-footer {
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #e9ecef;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .invite-dialog :deep(.el-dialog) {
    margin: 0;
    max-height: 100vh;
  }
  
  .invite-dialog :deep(.el-dialog__body) {
    padding: 16px;
  }
  
  .invite-container {
    max-height: 85vh;
  }
  
  .section-header h3 {
    font-size: 16px;
  }
  
  .list-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .invite-stats {
    flex-direction: column;
    gap: 12px;
  }
  
  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-align: left;
  }
  
  .stat-number {
    display: inline;
    margin-right: 8px;
  }
  
  .codes-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .code-card {
    padding: 12px;
  }
  
  .code-display {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .code-text {
    text-align: center;
    word-break: break-all;
  }
  
  .generate-btn {
    width: 100%;
    min-width: auto;
    text-align: center;
  }
  
  .alert-content {
    flex-direction: column;
    align-items: stretch;
    text-align: center;
  }
  
  .alert-content p {
    min-width: auto;
    margin-bottom: 8px;
  }
  
  .alert-actions {
    display: flex;
    justify-content: center;
  }
}
</style>
